package top.techqi.hamtools

import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.Menu
import android.view.MenuItem
import kotlinx.android.synthetic.main.activity_main.*
import top.techqi.droidbdf.pangu.base.BaseActivity
import top.techqi.droidbdf.pangu.util.LogV
import top.techqi.hamtools.func.VernierFragment
import top.techqi.hamtools.pref.SettingsActivity


class MainActivity : BaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        loadDefaultFragment()
    }

    override fun onContentChanged() {
        super.onContentChanged()
        setSupportActionBar(toolbar)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.main_toolbar, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.settings -> {
                startActivity(Intent(this, SettingsActivity::class.java))
                return true
            }
        }
        return false
    }

    override fun onAttachFragment(fragment: Fragment) {
        super.onAttachFragment(fragment)
        if (fragment is VernierFragment) toolbar.subtitle = fragment.subtitle
    }

    private fun loadDefaultFragment() {
        try {
            val info = packageManager.getActivityInfo(componentName, PackageManager.GET_META_DATA)
            val clazz = Class.forName(info.metaData.getString("fragment"))
            val ft = supportFragmentManager.beginTransaction()
            ft.replace(R.id.content, clazz.newInstance() as Fragment)
            ft.commitAllowingStateLoss()
        } catch (ex: Exception) {
            LogV.w("loadDefaultFragment" as? String, ex)
        }
    }
}
